package com.cskaoyan.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cskaoyan.mall.product.converter.dto.CategoryConverter;
import com.cskaoyan.mall.product.converter.dto.TrademarkConverter;
import com.cskaoyan.mall.product.dto.*;
import com.cskaoyan.mall.product.mapper.*;
import com.cskaoyan.mall.product.model.*;
import com.cskaoyan.mall.product.query.CategoryTrademarkParam;
import com.cskaoyan.mall.product.service.CategoryService;
import com.cskaoyan.mall.product.service.TrademarkService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.sql.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Macro_Ray
 * @since 2024/6/6 下午3:16
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryConverter categoryConverter;
    @Autowired
    TrademarkConverter trademarkConverter;
    @Autowired
    FirstLevelCategoryMapper firstLevelCategoryMapper;
    @Autowired
    SecondLevelCategoryMapper secondLevelCategoryMapper;
    @Autowired
    ThirdLevelCategoryMapper thirdLevelCategoryMapper;
    @Autowired
    CategoryTrademarkMapper categoryTrademarkMapper;
    @Autowired
    TrademarkMapper trademarkMapper;
    @Autowired
    CategoryHierarchyMapper categoryHierarchyMapper;

    /**
     * 获取一级分类
     */
    @Override
    public List<FirstLevelCategoryDTO> getFirstLevelCategory() {
        // 查询一级分类表
        List<FirstLevelCategory> firstLevelCategoryList = firstLevelCategoryMapper.selectList(null);
        // 返回DTO对象列表
        return categoryConverter.firstLevelCategoryPOs2DTOs(firstLevelCategoryList);
    }

    /**
     * 获取二级分类
     */
    @Override
    public List<SecondLevelCategoryDTO> getSecondLevelCategoryById(Long category1Id) {
        // 查询二级分类表，first_level_category_id = id的所有记录
        LambdaQueryWrapper<SecondLevelCategory> secondLevelCategoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        secondLevelCategoryLambdaQueryWrapper.eq(SecondLevelCategory::getFirstLevelCategoryId, category1Id);
        List<SecondLevelCategory> secondLevelCategoryList =
                secondLevelCategoryMapper.selectList(secondLevelCategoryLambdaQueryWrapper);
        // 返回DTO对象列表
        return categoryConverter.secondLevelCategoryPOs2DTOs(secondLevelCategoryList);
    }

    /**
     * 获取三级分类
     */
    @Override
    public List<ThirdLevelCategoryDTO> getThirdLevelCategoryById(Long category2Id) {
        // 查询三级分类表，second_level_category_id = id的所有记录
        LambdaQueryWrapper<ThirdLevelCategory> thirdLevelCategoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        thirdLevelCategoryLambdaQueryWrapper.eq(ThirdLevelCategory::getSecondLevelCategoryId, category2Id);
        List<ThirdLevelCategory> thirdLevelCategoryList =
                thirdLevelCategoryMapper.selectList(thirdLevelCategoryLambdaQueryWrapper);
        return categoryConverter.thirdLevelCategoryPOs2DTOs(thirdLevelCategoryList);
    }

    /**
     * 根据三级分类id获取分类品牌列表
     */
    @Override
    public List<TrademarkDTO> findCateTradeListByTLCId(Long category3Id) {
        // 查询分类品牌表，third_level_category_id = id的所有记录，封装到List<CategoryTrademark>中
        LambdaQueryWrapper<CategoryTrademark> cateTradeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cateTradeLambdaQueryWrapper.eq(CategoryTrademark::getThirdLevelCategoryId, category3Id);
        List<CategoryTrademark> categoryTrademarkList = categoryTrademarkMapper.selectList(cateTradeLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(categoryTrademarkList)) {
            List<Long> ids = new ArrayList<>();
            for (CategoryTrademark categoryTrademark : categoryTrademarkList) {
                Long trademarkId = categoryTrademark.getTrademarkId();
                ids.add(trademarkId);
            }
            List<Trademark> trademarks = trademarkMapper.selectBatchIds(ids);
            return trademarkConverter.trademarkPOs2DTOs(trademarks);
        }
        return null;
        // todo 为什么下面的代码返回前三个对象是null
        /*List<TrademarkDTO> cateTradeList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(categoryTrademarkList)) {
            for (CategoryTrademark categoryTrademark : categoryTrademarkList) {
                Trademark trademark = trademarkMapper.selectById(categoryTrademark.getTrademarkId());
                TrademarkDTO trademarkDTO = trademarkConverter.trademarkPO2DTO(trademark);
                if (categoryTrademark.getIsDeleted() == 0){
                    cateTradeList.add(trademarkDTO);
                }
            }
            System.out.println("获取到的分类品牌列表:" +cateTradeList);
            return cateTradeList;
        }
        return null;*/
    }

    /**根据三级分类id获取未关联的品牌列表，以便添加品牌*/
    @Override
    public List<TrademarkDTO> findUnLinkedTradeListByTLCId(Long category3Id) {
        // 查询分类品牌表中三级目录id和传过来的id相同的
        LambdaQueryWrapper<CategoryTrademark> cateTradeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cateTradeLambdaQueryWrapper.eq(CategoryTrademark::getThirdLevelCategoryId, category3Id);
        List<CategoryTrademark> categoryTrademarkList = categoryTrademarkMapper.selectList(cateTradeLambdaQueryWrapper);
        // 判断这个三级类目下有没有品牌
        if (!CollectionUtils.isEmpty(categoryTrademarkList)) {
            // 已关联的品牌
            List<Long> linkedIds = new ArrayList<>();
            for (CategoryTrademark categoryTrademark : categoryTrademarkList) {
                Long trademarkId = categoryTrademark.getTrademarkId();
                linkedIds.add(trademarkId);
            }
            // 查询未关联的品牌
            LambdaQueryWrapper<Trademark> trademarkLambdaQueryWrapper = new LambdaQueryWrapper<>();
            trademarkLambdaQueryWrapper.notIn(Trademark::getId, linkedIds);
            List<Trademark> trademarks = trademarkMapper.selectList(trademarkLambdaQueryWrapper);
            return trademarkConverter.trademarkPOs2DTOs(trademarks);
        }
        // 如果三级类目下没有品牌，就返回整个品牌列表
        List<Trademark> trademarks = trademarkMapper.selectList(null);
        return trademarkConverter.trademarkPOs2DTOs(trademarks);
    }

    /**添加品牌*/
    @Override
    public void saveCateTrademark(CategoryTrademarkParam categoryTrademarkParam) {
        List<Long> trademarkIdList = categoryTrademarkParam.getTrademarkIdList();
        for (Long trademarkId : trademarkIdList) {
            CategoryTrademark categoryTrademark = new CategoryTrademark();
            categoryTrademark.setThirdLevelCategoryId(categoryTrademarkParam.getCategory3Id());
            categoryTrademark.setTrademarkId(trademarkId);
            categoryTrademarkMapper.insert(categoryTrademark);
        }
    }

    /**删除品牌*/
    @Override
    public void removeCateTrademark(Long category3Id, Long trademarkId) {
        Map<String, Object> param = new HashMap<>();
        param.put("third_level_category_id", category3Id);
        param.put("trademark_id", trademarkId);
        categoryTrademarkMapper.deleteByMap(param);
    }

    /**根据三级分类id获取商品详情页中的分类层级*/
    @Override
    public CategoryHierarchyDTO getCateHierarchy(Long category3Id) {
        List<CategoryHierarchy> categoryHierarchies = categoryHierarchyMapper.selectCategoryHierarchy(category3Id);
        if (CollectionUtils.isEmpty(categoryHierarchies)){
            return null;
        }
        return categoryConverter.cateHierarchyPO2DTO(categoryHierarchies.get(0));
    }

    /**获取首页中的分类层级信息*/
    @Override
    public List<FirstLevelCategoryNodeDTO> getHomeCateHierarchyList() {
        // 创建结果集一级类目列表，返回的也是这个一级类目列表
        List<FirstLevelCategoryNodeDTO> homeCateHierarchyList = new ArrayList<>();
        // 传入三级类目是null，查询到所有分类层级信息
        List<CategoryHierarchy> categoryHierarchieList = categoryHierarchyMapper.selectCategoryHierarchy(null);
        // 流式操作，遍历分类列表，根据一级类目id进行分组，得到一个 key是一级类目id，value是对应的分类层级信息的map
        Map<Long, List<CategoryHierarchy>> mapByCategory1Id = categoryHierarchieList.stream()
                .collect(Collectors.groupingBy(CategoryHierarchy::getFirstLevelCategoryId));
        // 下标设为1
        int index = 1;
        // 遍历一级类目id的map，得到每个一级类目对应的分类层级信息
        for (Map.Entry<Long, List<CategoryHierarchy>> mapEntryByCate1Id : mapByCategory1Id.entrySet()) {
            // 获取一级类目id
            Long category1Id = mapEntryByCate1Id.getKey();
            // 获取一级类目id这个组中对应的分类层级信息
            List<CategoryHierarchy> category23List = mapEntryByCate1Id.getValue();
            // 定义一级类目结构
            FirstLevelCategoryNodeDTO firstLevelCategoryNodeDTO = new FirstLevelCategoryNodeDTO();
            firstLevelCategoryNodeDTO.setCategoryId(category1Id);
            firstLevelCategoryNodeDTO.setCategoryName(category23List.get(0).getFirstLevelCategoryName());
            firstLevelCategoryNodeDTO.setIndex(index);
            index++;
            // 一级类目下的categoryChild列表
            List<SecondLevelCategoryNodeDTO> categoryChild1List = bulidCategory2List(category23List);
            // 放入DTO对象中
            firstLevelCategoryNodeDTO.setCategoryChild(categoryChild1List);
            // 放入结果集中
            homeCateHierarchyList.add(firstLevelCategoryNodeDTO);
        }
        return homeCateHierarchyList;
    }

    private static @NotNull List<SecondLevelCategoryNodeDTO> bulidCategory2List(List<CategoryHierarchy> category23List) {
        // 创建结果集的二级类目列表
        List<SecondLevelCategoryNodeDTO> categoryChild1List = new ArrayList<>();
        // 遍历类目列表，根据二级类目id进行分组，得到一个 key是二级类目id，value是对应的分类层级信息的map
        Map<Long, List<CategoryHierarchy>> mapByCategory2Id = category23List.stream()
                .collect(Collectors.groupingBy(CategoryHierarchy::getSecondLevelCategoryId));
        for (Map.Entry<Long, List<CategoryHierarchy>> mapEntryByCate2Id : mapByCategory2Id.entrySet()) {
            Long category2Id = mapEntryByCate2Id.getKey();
            List<CategoryHierarchy> category3List = mapEntryByCate2Id.getValue();
            // 定义二级类目结构
            SecondLevelCategoryNodeDTO secondLevelCategoryNodeDTO = new SecondLevelCategoryNodeDTO();
            secondLevelCategoryNodeDTO.setCategoryId(category2Id);
            secondLevelCategoryNodeDTO.setCategoryName(category3List.get(0).getSecondLevelCategoryName());
            // 二级类目下的categoryChild列表
            List<ThirdLevelCategoryNodeDTO> categoryChild2List = buildCategory3List(category3List);

            secondLevelCategoryNodeDTO.setCategoryChild(categoryChild2List);
            categoryChild1List.add(secondLevelCategoryNodeDTO);
        }
        return categoryChild1List;
    }

    private static @NotNull ArrayList<ThirdLevelCategoryNodeDTO> buildCategory3List(List<CategoryHierarchy> category3List) {
        // 定义结果集的三级类目列表
        ArrayList<ThirdLevelCategoryNodeDTO> categoryChild2List = new ArrayList<>();
        // 遍历二级类目id对应的分类升级信息，得到三级类目信息
        for (CategoryHierarchy category3 : category3List) {
            ThirdLevelCategoryNodeDTO thirdLevelCategoryNodeDTO = new ThirdLevelCategoryNodeDTO();
            thirdLevelCategoryNodeDTO.setCategoryId(category3.getThirdLevelCategoryId());
            thirdLevelCategoryNodeDTO.setCategoryName(category3.getThirdLevelCategoryName());
            categoryChild2List.add(thirdLevelCategoryNodeDTO);
        }
        return categoryChild2List;
    }
}
